package com.taichuan.selfcheck.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 将文本从最后一行开始读取
 * TODO 未调用，但子方法有使用
 */
public class AlterReadText {
    public static void main(String[] args) {
        String fileName = "C:\\Users\\admin\\Desktop\\test.txt";
        RandomAccessFile r = null;
        try {
            r = new RandomAccessFile(fileName, "r");
            long start = r.getFilePointer();
            long nextend = start + r.length() - 1;
            String result;
            r.seek(nextend);
            int c = -1;
            while (nextend >= start) {
                c = r.read();
                if (c == '\n' || c == '\r') {
                    result = r.readLine();
                    System.out.println(new String(result.getBytes("ISO-8859-1"), "GBK"));
                    //TODO 此处可以自行对result进行操作
                    nextend--;
                }
                nextend--;
                if(nextend>=0) {
                    r.seek(nextend);
                    if (nextend == 0) {// 当文件指针退至文件开始处，输出第一行
                        System.out.println(new String(r.readLine().getBytes("ISO-8859-1"), "GBK"));
                    }
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (r != null)
                try {
                    r.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}
